<template>
  <view class="staff-detail-page">
    <view class="page-header">
      <text class="page-title">员工详情</text>
      <view class="header-actions">
        <button class="btn btn-default" @click="handleBack">返回</button>
        <button class="btn btn-primary" @click="handleEdit">编辑</button>
        <button v-if="staff.is_active" class="btn btn-danger" @click="handleDelete">设为离职</button>
        <button v-else class="btn btn-success" @click="handleEnable">设为在职</button>
      </view>
    </view>

    <view v-if="loading" class="loading-container">
      <view class="loading-spinner"></view>
      <text class="loading-text">加载中...</text>
    </view>

    <view v-else class="detail-content">
      <view class="detail-card">
        <view class="card-header">
          <text class="card-title">基本信息</text>
          <view :class="['status-badge', 'status-' + staff.working_status]">
            {{ getWorkingStatusText(staff.working_status) }}
          </view>
        </view>
        <view class="card-body">
          <view v-if="staff.photo && staff.photo.url" class="photo-section">
            <image :src="staff.photo.url" mode="aspectFill" class="staff-photo" />
          </view>
          
          <view class="detail-row">
            <text class="label">员工姓名</text>
            <text class="value highlight">{{ staff.staff_name || '-' }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">员工类型</text>
            <text class="value">{{ staff.staff_type_text || '-' }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">职位</text>
            <text class="value">{{ staff.position || '-' }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">部门</text>
            <text class="value">{{ staff.department || '-' }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">入职日期</text>
            <text class="value">{{ formatDate(staff.hire_date) }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">学历背景</text>
            <text class="value">{{ staff.education_background || '-' }}</text>
          </view>
          
          <view v-if="staff.introduction" class="detail-row detail-row-vertical">
            <text class="label">个人简介</text>
            <text class="value">{{ staff.introduction }}</text>
          </view>
        </view>
      </view>
      
      <view v-if="staff.user_info" class="detail-card">
        <view class="card-header">
          <text class="card-title">关联账户信息</text>
          <view :class="['status-badge', staff.user_info.status === 0 ? 'status-active' : 'status-inactive']">
            {{ staff.user_info.status === 0 ? '正常' : '禁用' }}
          </view>
        </view>
        <view class="card-body">
          <view class="detail-row">
            <text class="label">用户名</text>
            <text class="value">{{ staff.user_info.username || '-' }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">昵称</text>
            <text class="value">{{ staff.user_info.nickname || '-' }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">手机号</text>
            <text class="value">{{ staff.user_info.mobile || '-' }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">邮箱</text>
            <text class="value">{{ staff.user_info.email || '-' }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">角色</text>
            <text class="value">{{ getRoleText(staff.user_info.role) }}</text>
          </view>
        </view>
      </view>

      <view class="detail-card">
        <view class="card-header">
          <text class="card-title">时间信息</text>
        </view>
        <view class="card-body">
          <view class="detail-row">
            <text class="label">创建时间</text>
            <text class="value">{{ formatTime(staff.create_time) }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">更新时间</text>
            <text class="value">{{ formatTime(staff.update_time) }}</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'

const loading = ref(true)
const staffId = ref('')
const staff = reactive({
  _id: '',
  staff_name: '',
  user_id: '',
  staff_type: 0,
  staff_type_text: '',
  position: '',
  department: '',
  hire_date: null,
  photo: null,
  education_background: '',
  introduction: '',
  working_status: 0,
  is_active: true,
  create_time: null,
  update_time: null,
  user_info: null
})

onMounted(async () => {
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  staffId.value = currentPage.options.id || ''
  
  if (!staffId.value) {
    uni.showToast({ title: '缺少员工ID', icon: 'none' })
    setTimeout(() => {
      uni.redirectTo({ url: '/pages/business/staff_users/list' })
    }, 1500)
    return
  }
  
  await loadStaffData()
  loading.value = false
})

async function loadStaffData() {
  try {
    // 使用云对象方法获取员工用户详情
    const dhStaffUsers = uniCloud.importObject('dh-staff_users')
    const result = await dhStaffUsers.getStaffUserById(staffId.value)
    
    if (result.code === 200 && result.data) {
      Object.assign(staff, result.data)
    } else {
      throw new Error(result.message || '员工不存在')
    }
  } catch (err) {
    console.error('加载员工数据失败:', err)
    uni.showToast({ title: err.message || '加载失败', icon: 'none' })
    setTimeout(() => {
      uni.redirectTo({ url: '/pages/business/staff_users/list' })
    }, 1500)
  }
}

function getWorkingStatusText(status) {
  const statusMap = { 0: '在职', 1: '请假', 2: '外出' }
  return statusMap[status] || '未知'
}

function getRoleText(role) {
  const roleMap = {
    'admin': '超级管理员',
    'manager': '管理员',
    'director': '院长',
    'administrative': '行政',
    'finance': '财务',
    'nurse': '护士',
    'doctor': '医生',
    'staff': '员工'
  }
  
  // 处理角色是数组的情况
  if (Array.isArray(role)) {
    // 优先显示员工角色（非user角色）
    const staffRole = role.find(r => r !== 'user')
    if (staffRole) {
      return roleMap[staffRole] || staffRole || '未知'
    }
    // 如果只有user角色
    return role.length > 0 ? (roleMap[role[0]] || role[0]) : '未知'
  }
  
  return roleMap[role] || role || '未知'
}

function formatDate(timestamp) {
  if (!timestamp) return '-'
  // 处理uniCloud timestamp类型
  let dateValue = timestamp
  if (typeof timestamp === 'object' && timestamp.$date) {
    dateValue = timestamp.$date
  }
  const date = new Date(dateValue)
  // 检查日期是否有效
  if (isNaN(date.getTime())) return '-'
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

function formatTime(timestamp) {
  if (!timestamp) return '-'
  // 处理uniCloud timestamp类型
  let dateValue = timestamp
  if (typeof timestamp === 'object' && timestamp.$date) {
    dateValue = timestamp.$date
  }
  const date = new Date(dateValue)
  // 检查日期是否有效
  if (isNaN(date.getTime())) return '-'
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hour = String(date.getHours()).padStart(2, '0')
  const minute = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hour}:${minute}`
}

function handleBack() {
  uni.redirectTo({ url: '/pages/business/staff_users/list' })
}

function handleEdit() {
  uni.redirectTo({ url: `/pages/business/staff_users/edit?id=${staffId.value}` })
}

function handleDelete() {
  uni.showModal({
    title: '确认离职',
    content: '确定要将该员工设置为离职状态吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          uni.showLoading({ title: '操作中...' })
          const dhStaffUsers = uniCloud.importObject('dh-staff_users')
          const result = await dhStaffUsers.updateStaff(staffId.value, {
            is_active: false
          })
          uni.hideLoading()
          
          if (result.code === 200) {
            uni.showToast({ title: '已设为离职', icon: 'success' })
            setTimeout(() => {
              uni.redirectTo({ url: '/pages/business/staff_users/list' })
            }, 1500)
          } else {
            uni.showToast({ title: result.message || '操作失败', icon: 'none' })
          }
        } catch (err) {
          console.error('操作失败:', err)
          uni.hideLoading()
          uni.showToast({ title: err.message || '操作失败', icon: 'none' })
        }
      }
    }
  })
}

function handleEnable() {
  uni.showModal({
    title: '确认在职',
    content: '确定要将该员工设置为在职状态吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          uni.showLoading({ title: '操作中...' })
          const dhStaffUsers = uniCloud.importObject('dh-staff_users')
          const result = await dhStaffUsers.updateStaff(staffId.value, {
            is_active: true
          })
          uni.hideLoading()
          
          if (result.code === 200) {
            uni.showToast({ title: '已设为在职', icon: 'success' })
            setTimeout(() => {
              uni.redirectTo({ url: '/pages/business/staff_users/list' })
            }, 1500)
          } else {
            uni.showToast({ title: result.message || '操作失败', icon: 'none' })
          }
        } catch (err) {
          console.error('操作失败:', err)
          uni.hideLoading()
          uni.showToast({ title: err.message || '操作失败', icon: 'none' })
        }
      }
    }
  })
}
</script>

<style lang="scss" scoped>
.staff-detail-page {
  min-height: 100vh;
  background: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.page-header {
  background: #fff;
  padding: 30rpx 40rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  border-bottom: 1rpx solid #e0e0e0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 20rpx;
}

.page-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.header-actions {
  display: flex;
  gap: 16rpx;
  flex-wrap: wrap;
}

.btn {
  padding: 12rpx 24rpx;
  font-size: 28rpx;
  border-radius: 8rpx;
  border: none;
  white-space: nowrap;
  min-width: 100rpx;
  text-align: center;
  
  &.btn-default {
    background: #f5f5f5;
    color: #666;
  }
  
  &.btn-primary {
    background: #007aff;
    color: #fff;
  }
  
  &.btn-danger {
    background: #ff3b30;
    color: #fff;
  }
  
  &.btn-success {
    background: #34c759;
    color: #fff;
  }
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .header-actions {
    width: 100%;
  }
  
  .btn {
    flex: 1;
    min-width: 0;
  }
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 200rpx 0;
}

.loading-spinner {
  width: 80rpx;
  height: 80rpx;
  border: 6rpx solid #f3f3f3;
  border-top: 6rpx solid #007aff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 30rpx;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  font-size: 28rpx;
  color: #666;
}

.detail-content {
  flex: 1;
  padding: 20rpx;
}

.detail-card {
  background: #fff;
  border-radius: 8rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.08);
}

.card-header {
  background: #fafafa;
  padding: 24rpx 32rpx;
  border-bottom: 1rpx solid #e0e0e0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.status-badge {
  padding: 8rpx 20rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
  
  &.status-0 {
    background: #d1fae5;
    color: #065f46;
  }
  
  &.status-1 {
    background: #fef3c7;
    color: #92400e;
  }
  
  &.status-2 {
    background: #dbeafe;
    color: #1e40af;
  }
  
  &.status-active {
    background: #e8f5e9;
    color: #2e7d32;
  }
  
  &.status-inactive {
    background: #ffebee;
    color: #c62828;
  }
}

.card-body {
  padding: 32rpx;
}

.photo-section {
  display: flex;
  justify-content: flex-start;
  margin-bottom: 32rpx;
  padding-bottom: 32rpx;
  border-bottom: 1rpx solid #e0e0e0;
}

.staff-photo {
  width: 600rpx;
  height: 600rpx;
  border-radius: 8rpx;
  object-fit: cover;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.detail-row {
  display: flex;
  margin-bottom: 24rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
  
  &.detail-row-vertical {
    flex-direction: column;
    
    .label {
      margin-bottom: 12rpx;
    }
    
    .value {
      line-height: 1.6;
    }
  }
}

.label {
  font-size: 28rpx;
  color: #999;
  min-width: 180rpx;
}

.value {
  flex: 1;
  font-size: 28rpx;
  color: #333;
  word-break: break-all;
  
  &.highlight {
    font-weight: bold;
    color: #007aff;
  }
}
</style>
